const { pool } = require('../config/db');
const Router = require('koa-router');
const router = new Router({ prefix: '/categories' });

const authMiddleware = require('../middleware/auth');

// 后台：创建分类
router.post('/', authMiddleware, async (ctx) => {
  try {
    const { name } = ctx.request.body;

    // 输入验证
    if (!name || typeof name !== 'string' || name.trim() === '') {
      ctx.status = 400;
      return ctx.body = { message: '分类名称不能为空', code: 400 };
    }

    const trimmedName = name.trim();

    // 检查长度
    if (trimmedName.length > 50) {
      ctx.status = 400;
      return ctx.body = { message: '分类名称不能超过50个字符', code: 400 };
    }

    // 前置检查：验证分类名称是否已存在
    const [existing] = await pool.query('SELECT id FROM categories WHERE name = ?', [trimmedName]);
    if (existing.length > 0) {
      ctx.status = 409;
      return ctx.body = {
        message: '分类名称已存在，请使用其他名称',
        code: 409
      };
    }

    const [result] = await pool.query('INSERT INTO categories (name) VALUES (?)', [trimmedName]);
    console.log('创建分类成功:', result);

    ctx.status = 201;
    ctx.body = {
      id: result.insertId,
      message: '分类创建成功',
      code: 200
    };
  } catch (error) {
    console.error('创建分类失败:', error);

    // 处理重复名称（双重保险）
    if (error.code === 'ER_DUP_ENTRY') {
      ctx.status = 409;
      return ctx.body = {
        message: '分类名称已存在，请使用其他名称',
        code: 409
      };
    }

    // 其他错误
    ctx.status = 500;
    ctx.body = {
      message: '创建分类失败，请稍后重试',
      code: 500
    };
  }
});

// 后台：更新分类
router.put('/:id', authMiddleware, async (ctx) => {
  try {
    const { id } = ctx.params;
    const { name } = ctx.request.body;

    // 参数验证 - 分类ID
    const categoryId = parseInt(id);
    if (isNaN(categoryId) || categoryId <= 0) {
      ctx.status = 400;
      return ctx.body = {
        success: false,
        message: '无效的分类ID',
        code: 400
      };
    }

    // 输入验证 - 分类名称
    if (!name || typeof name !== 'string' || name.trim() === '') {
      ctx.status = 400;
      return ctx.body = {
        success: false,
        message: '分类名称不能为空',
        code: 400
      };
    }

    const trimmedName = name.trim();

    // 检查长度
    if (trimmedName.length > 50) {
      ctx.status = 400;
      return ctx.body = {
        success: false,
        message: '分类名称不能超过50个字符',
        code: 400
      };
    }

    // 检查分类是否存在
    const [existing] = await pool.query('SELECT id FROM categories WHERE id = ?', [categoryId]);
    if (existing.length === 0) {
      ctx.status = 404;
      return ctx.body = {
        success: false,
        message: '分类不存在',
        code: 404
      };
    }

    // 检查新名称是否已存在（排除自己）
    const [duplicate] = await pool.query('SELECT id FROM categories WHERE name = ? AND id != ?', [trimmedName, categoryId]);
    if (duplicate.length > 0) {
      ctx.status = 409;
      return ctx.body = {
        success: false,
        message: '分类名称已存在',
        code: 409
      };
    }

    // 执行更新
    const [result] = await pool.query('UPDATE categories SET name = ? WHERE id = ?', [trimmedName, categoryId]);

    // 统一响应格式
    ctx.body = {
      success: true,
      message: '分类更新成功',
      code: 200
    };

  } catch (error) {
    console.error('更新分类失败:', error);

    // 处理重复名称
    if (error.code === 'ER_DUP_ENTRY') {
      ctx.status = 409;
      return ctx.body = {
        success: false,
        message: '分类名称已存在，请使用其他名称',
        code: 409
      };
    }

    // 其他错误
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '更新分类失败，请稍后重试',
      code: 500
    };
  }
});

// 后台：删除分类（只接收数组）
router.delete('/', authMiddleware, async (ctx) => {
  try {
    const requestBody = ctx.request.body;

    // 只接收数组格式
    let targetIds = [];

    // 1. 优先检查直接数组格式：[123, 456, 789]
    if (Array.isArray(requestBody)) {
      targetIds = requestBody;
    }
    // 2. 检查 {ids: [...]} 格式
    else if (requestBody && requestBody.ids && Array.isArray(requestBody.ids)) {
      targetIds = requestBody.ids;
    } else if (typeof requestBody.ids === 'string') {
      targetIds.push(requestBody.ids);
    }
    // 3. 其他情况都视为无效参数
    else {
      ctx.status = 400;
      return ctx.body = {
        success: false,
        message: '参数错误：请提供分类ID数组',
        code: 400
      };
    }

    // 验证数组不能为空
    if (targetIds.length === 0) {
      ctx.status = 400;
      return ctx.body = {
        success: false,
        message: '参数错误：分类ID数组不能为空',
        code: 400
      };
    }

    // 转换并验证所有ID（确保都是数字）
    const validIds = [];
    for (const id of targetIds) {
      const categoryId = parseInt(id);
      if (isNaN(categoryId) || categoryId <= 0) {
        ctx.status = 400;
        return ctx.body = {
          success: false,
          message: `参数错误：无效的分类ID ${id}`,
          code: 400
        };
      }
      validIds.push(categoryId);
    }

    // 检查分类是否存在
    const placeholders = validIds.map(() => '?').join(',');
    const [existing] = await pool.query(
      `SELECT id FROM categories WHERE id IN (${placeholders})`,
      validIds
    );

    if (existing.length === 0) {
      ctx.status = 404;
      return ctx.body = {
        success: false,
        message: '分类不存在',
        code: 404
      };
    }

    // 批量删除分类
    const [deleteResult] = await pool.query(
      `DELETE FROM categories WHERE id IN (${placeholders})`,
      validIds
    );

    // 根据删除数量返回不同的响应
    if (validIds.length === 1) {
      // 单个删除：保持原有响应格式
      ctx.body = {
        success: true,
        message: '分类删除成功',
        data: {
          id: validIds[0]
        },
        code: 200
      };
    } else {
      // 批量删除：返回批量信息
      ctx.body = {
        success: true,
        message: `成功删除 ${deleteResult.affectedRows} 个分类`,
        data: {
          deletedCount: deleteResult.affectedRows,
          deletedIds: validIds
        },
        code: 200
      };
    }

  } catch (error) {
    console.error('删除分类失败:', error);
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '删除分类失败，请稍后重试，可能该分类正在被使用',
      code: 500
    };
  }
});

// 后台：获取所有分类+搜索
router.get('/', async (ctx) => {
  try {
    const { keyword, page = 1, pageSize = 10 } = ctx.query;

    // 参数验证
    const currentPage = parseInt(page);
    const limit = parseInt(pageSize);

    if (isNaN(currentPage) || currentPage < 1) {
      ctx.status = 400;
      return ctx.body = {
        success: false,
        message: '页码参数错误',
        code: 400
      };
    }

    if (isNaN(limit) || limit < 1 || limit > 100) {
      ctx.status = 400;
      return ctx.body = {
        success: false,
        message: '每页条数参数错误（1-100）',
        code: 400
      };
    }

    let sql = 'SELECT id, name FROM categories';
    let countSql = 'SELECT COUNT(*) as total FROM categories';
    const params = [];
    const countParams = [];

    // 如果有关键词，添加搜索条件
    if (keyword && keyword.trim()) {
      const searchKeyword = `%${keyword.trim()}%`;
      sql += ' WHERE name LIKE ?';
      countSql += ' WHERE name LIKE ?';
      params.push(searchKeyword);
      countParams.push(searchKeyword);
    }

    // 添加排序
    sql += ' ORDER BY id ASC';

    // 添加分页
    const offset = (currentPage - 1) * limit;
    sql += ' LIMIT ? OFFSET ?';
    params.push(limit, offset);

    // 执行查询
    const [rows] = await pool.query(sql, params);
    const [countResult] = await pool.query(countSql, countParams);

    // 数据处理和格式化
    const categories = rows.map(category => ({
      id: category.id,
      name: category.name.trim()
    }));

    // 返回响应
    ctx.body = {
      success: true,
      message: keyword ? '分类搜索成功' : '分类列表获取成功',
      data: {
        list: categories,
        total: countResult[0].total,
        page: currentPage,
        pageSize: limit,
        totalPages: Math.ceil(countResult[0].total / limit)
      },
      code: 200
    };

  } catch (error) {
    console.error('搜索分类失败:', error);
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '搜索分类失败，请稍后重试',
      code: 500
    };
  }
});


module.exports = router;